<?php

namespace App\Models;

use App\Enums\UserType;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class AssistantRank extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'user_id', 'store_id',
        'total_minutes', 'total_assistant_minutes', 'total_assistant_count', 'total_point',
        'total_inner_virtual_minutes', 'total_outer_virtual_minutes',
        'count_date',
    ];

    protected $casts = [
        'count_date' => 'date',
    ];

    public function assistant()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function store()
    {
        return $this->belongsTo(Store::class);
    }

    public static function createDailyRecord($date)
    {
        $users = User::where('type', UserType::Assistant)->get();

        foreach ($users as $user) {
            //先判断是否已经存在记录
            if (AssistantRank::where('user_id', $user->id)->where('count_date', $date)->exists())
                continue;

            //创建记录
            AssistantRank::create([
                'user_id' => $user->id,
                'store_id' => $user->store_id,
                'count_date' => $date,
            ]);
        }
    }
}
